package com.dlwx.parttimetalent.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.ui.ChatActivity;
import com.dlwx.parttimetalent.ui.MsgActivity;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.ChatInter;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;


public class ThreeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.tv_sys)
    TextView tvSys;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_trade)
    TextView tvTrade;
    Unbinder unbinder;
    @BindView(R.id.list)
    EaseConversationList conversationListView;
    @BindView(R.id.fl_error_item)
    FrameLayout errorItemContainer;
    @BindView(R.id.fl_count)
    FrameLayout flCount;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.ll_1)
    LinearLayout ll1;
    @BindView(R.id.ll_2)
    LinearLayout ll2;
    @BindView(R.id.ll_3)
    LinearLayout ll3;


    private String mParam1;
    private String mParam2;
    private RxPermissions rxPermissions;
    private IntentFilter intentFilter;
    private MyBrodcastReceiver myBroadcastReceiver;
    private QBadgeView baggeView;
    private Badge bagge2,bagge1,bagge3;
    private String conId;

    public ThreeFragment() {
        // Required empty public constructor
    }

    public static ThreeFragment newInstance(String param1, String param2) {
        ThreeFragment fragment = new ThreeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        View view = inflater.inflate(R.layout.fragment_three, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        conId= (String) SPUtils.get(getActivity(),Constant.ConId,"");
        LogUtils.i("conid:"+conId);
        refreshHx("");
        int sytNum = (int) SPUtils.get(getActivity(), Constant.MSG_S, 0);
        int orderNum = (int) SPUtils.get(getActivity(), Constant.MSG_O, 0);
        int tradeNum = (int) SPUtils.get(getActivity(), Constant.MSG_T, 0);
        if(bagge1==null){
            bagge1=new QBadgeView(getActivity()).bindTarget(ll1);
        }
        if (sytNum > 0) {
            bagge1.setBadgeNumber(sytNum);
        }else{
            bagge1.setBadgeNumber(0);
        }

        if(bagge2==null){
            bagge2=new QBadgeView(getActivity()).bindTarget(ll2);
        }
        if (orderNum > 0) {
            bagge2.setBadgeNumber(orderNum);
        }else{
            bagge2.setBadgeNumber(0);
        }

        if(bagge3==null){
            bagge3=new QBadgeView(getActivity()).bindTarget(ll3);
        }
        if (tradeNum > 0) {
            bagge3.setBadgeNumber(tradeNum);
        }else {
            bagge3.setBadgeNumber(0);
        }
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }

    protected void initView() {
        rxPermissions = new RxPermissions(getActivity());
        tvMiddleTitle.setText("消息");
        tvMiddleTitle.setVisibility(View.VISIBLE);
        intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_HX);

        myBroadcastReceiver = new MyBrodcastReceiver();
        getActivity().registerReceiver(myBroadcastReceiver, intentFilter);

    }

    private void refreshHx(String ll) {
        if (conversationListView == null) {
            return;
        }

        //初始化，参数为会话列表集合
        final List<EMConversation> conversationList = new ArrayList<>();
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
//        if(!TextUtils.isEmpty(conId)){
        LogUtils.i("-->"+conId);
        for (Map.Entry<String, EMConversation> entry : conversations.entrySet()) {
            EMConversation conver = entry.getValue();
            if(conver!=null&&conver.getLastMessage()!=null){
//                entry.getValue().
                if(TextUtils.equals(conId,conver.conversationId())){
                    conversationList.add(0,conver);
                }else{
                    conversationList.add(conver);
                }
            }
//          }
        }
        conversationListView.setCallBack(new ChatInter() {
            @Override
            public void callBack(final EMConversation conversation) {
                rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                                    intent.putExtra(EaseConstant.EXTRA_USER_ID, conversation.conversationId());
                                    SPUtils.put(getActivity(),Constant.ConId,conversation.conversationId());
                                    //这个人和你聊天的最后一条消息里面看是谁发的。判断方法就是取出这条消息发的人的环信id与你自己本地存储的环信id做匹配。是你发的与不是你发的，传入的值正好相反。
                                    int id = (int) SPUtils.get(getContext(), EaseConstant.USER_ID, 0);
                                    if (conversation.getLastMessage() == null) {
                                        return;
                                    }
                                    if (!conversation.getLastMessage().getFrom().equals("" + id)) {
                                        intent.putExtra("to_headportrait", conversation.getLastMessage().getStringAttribute("from_headportrait", ""));
                                        intent.putExtra("to_username", conversation.getLastMessage().getStringAttribute("from_username", ""));
                                        intent.putExtra("to_user_id", conversation.getLastMessage().getStringAttribute("from_user_id", ""));
                                    } else {
                                        intent.putExtra("to_headportrait", conversation.getLastMessage().getStringAttribute("to_headportrait", ""));
                                        intent.putExtra("to_username", conversation.getLastMessage().getStringAttribute("to_username", ""));
                                        intent.putExtra("to_user_id", conversation.getLastMessage().getStringAttribute("to_user_id", ""));
                                    }
                                    startActivity(intent);
                                }
                            }
                        });
            }
        });
        conversationListView.init(conversationList);
//刷新列表
        conversationListView.refresh();
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final EMConversation conversation = conversationList.get(position);
                rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                                    conId=conversationList.get(position).conversationId();
                                    intent.putExtra(EaseConstant.EXTRA_USER_ID, conversationList.get(position).conversationId());
                                    //这个人和你聊天的最后一条消息里面看是谁发的。判断方法就是取出这条消息发的人的环信id与你自己本地存储的环信id做匹配。是你发的与不是你发的，传入的值正好相反。
                                    int id = (int) SPUtils.get(getContext(), EaseConstant.USER_ID, 0);
                                    if (conversation.getLastMessage() == null) {
                                        return;
                                    }
                                    if (!conversation.getLastMessage().getFrom().equals("" + id)) {
                                        intent.putExtra("to_headportrait", conversation.getLastMessage().getStringAttribute("from_headportrait", ""));
                                        intent.putExtra("to_username", conversation.getLastMessage().getStringAttribute("from_username", ""));
                                        intent.putExtra("to_user_id", conversation.getLastMessage().getStringAttribute("from_user_id", ""));
                                    } else {
                                        intent.putExtra("to_headportrait", conversation.getLastMessage().getStringAttribute("to_headportrait", ""));
                                        intent.putExtra("to_username", conversation.getLastMessage().getStringAttribute("to_username", ""));
                                        intent.putExtra("to_user_id", conversation.getLastMessage().getStringAttribute("to_user_id", ""));
                                    }
                                    startActivity(intent);
                                }
                            }
                        });
            }
        });
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
//        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_sys, R.id.tv_order, R.id.tv_trade})
    public void onViewClicked(View view) {
    ;
        Intent i = new Intent(getActivity(), MsgActivity.class);
        switch (view.getId()) {
            case R.id.tv_sys:
                SPUtils.put(getActivity(),Constant.MSG_S,0);
                i.putExtra("type", Constant.MSG_SYS);
                startActivity(i);
                break;
            case R.id.tv_order:
                SPUtils.put(getActivity(),Constant.MSG_O,0);
                i.putExtra("type", Constant.MSG_ORDER);
                startActivity(i);
                break;
            case R.id.tv_trade:
                SPUtils.put(getActivity(),Constant.MSG_T,0);
                i.putExtra("type", Constant.MSG_TRADE);
                startActivity(i);
                break;
        }
    }

    public class MyBrodcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), Constant.ACTION_HX)) {
                 conId=intent.getStringExtra("conId");
                SPUtils.put(getActivity(),Constant.ConId,conId);
                refreshHx(conId);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(myBroadcastReceiver);
    }
}
